package com.tlvip.arithmetic.ch04;

/**
 * <p>description：</p>
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 1/24/21</p>
 * Author mac
 *
 * @version 1.0
 */
public class ArrayStack<Item> implements MyStack<Item> {
    private Item[] a = (Item[]) new Object[1];

    private int n = 0; // 初始的元素数量

    public ArrayStack(int cap) {
        a = (Item[]) new Object[cap];
    }

    @Override
    public MyStack<Item> push(Item item) {
        judgeSize();
        a[n++] = item;
        return null;
    }

    private void judgeSize() {
        if (n >= a.length) {
            resize(2 * a.length);
        } else if (n > 0 && n < a.length / 2) {
            // 缩容
            resize(a.length / 2);
        }
    }

    private void resize(int size) {
        Item[] temp = (Item[]) new Object[size];
        for (int i = 0; i < n; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }


    @Override
    public Item pop() {
        if (n <= 0) {
            return null;
        }
        Item item = a[--n];
        a[n] = null;
        return item;
    }

    @Override
    public int size() {
        return n;
    }

    @Override
    public boolean isEmpty() {
        return n == 0;
    }

    public static void main(String[] args) {
        ArrayStack<Integer> arrayStack = new ArrayStack(5);
        for (int i = 0; i < 5; i++) {
            arrayStack.push(i);
        }
        for (int i = 0; i < 5; i++) {
            System.out.println(arrayStack.pop());
        }
    }
}
